<?php
global $conf;
$conf['es'] = array(
    'hosts' => '127.0.0.1:9200',
);
function getProvince() {
    $all = file_get_contents('data.txt');
    $all = json_decode($all, true);
    $all = array_slice($all["province"], 0, 3);
    foreach ($all as $province) {
        foreach ($province["data"] as $city) {
            foreach ($city['data'] as $qu) {
                $list[$qu['name']] = $city['name'];
            }
        }
    }
    return $list;
}
function connect_mysql() {
    global $conf;
    $conf['mysql'] = @mysql_connect("localhost","root","") or die("database error".mysql_error());
    mysql_select_db("baiduRoboot",$conf['mysql']) or die("database call error".mysql_error());
    mysql_query("set names utf8");
}
function close_mysql() {
    global $conf;
    //mysql_close($conf['mysql']);
}
function getCity() {
	connect_mysql();
    $sql = 'SELECT name,code FROM baidu_city';
    $res = mysql_query($sql);
    while ($row = mysql_fetch_assoc($res)) {
        $city[$row['name']] = $row['code'];
    }
    $city['涿州市'] = $city['保定市'];
    return $city;
}
function getDiffxiaoqu($type=2, $file= "./log/diff_xiaoqu_es_esf.log") {
    $cityList = getCity();
    $province = getProvince();
    $fp = fopen($file, 'r');
    $data = array();
    while($line = trim(fgets($fp))) {
        if ($line[0].$line[1] == '0:') {
            @list($type, $addr, $geo, $keyword) = explode("\t", trim($line));
            $item = getKeyWordCity($keyword, $addr, $cityList, $province);
            $item['baidu_geo'] = $geo;
            $data[] = $item;
//             foreach (array("北京市","保定市", "张家口市", "唐山市", "廊坊市", "天津市") as $city) {
//                 $data[] = array(
//                     'city' => $city,
//                     'code' => $cityList[$city],
//                     'name' => $keyword,
//                 );
//             }
        }
    }
    fclose($fp);
    return $data;
}
function getXiaoquKeyword($city='110000',$limit='5000', $last_id=0) {
	connect_mysql();
    $cityList = getCity();
    $province = getProvince();
    $sql = "SELECT b_id,b_name,b_address FROM rb_business" 
     . " WHERE b_id >".$last_id." and b_city=110000 and b_industry=24 order by b_id asc LIMIT ".$limit;
    
    echo $sql, "\n";
    $res = mysql_query($sql);
    while ($row = mysql_fetch_assoc($res)) {
        $data[$row['b_id']] = getKeyWordCity($row['b_name'], $row['b_address'], $cityList, $province);
    }
    return $data;
}
function getKeyWordCity($keyword, $addr, $cityList, $province) {
    
    $b_address = $addr;
    $city = strstr($addr, "省");
    $city !== false && $addr = $city;
    $city = strstr($addr, "市", true);
    if ($city === false) {
        foreach ($province as $c => $p) {
            if(strstr($addr, $c) !== false) {
                $city = $p;
            }
        }
    } else {
        $city .= '市';
    }

    in_array($city, $province) || $city = '北京市';
    return  array(
        'city' => $city,
        'code' => $cityList[$city],
        'name' => $keyword,
        'addr' => $addr,
    );
}
function batchInsert($datas, $tablename, $need_update = false){
	connect_mysql();
    $cols = array_keys(current($datas));
    $value= '';
    foreach ($datas as $row){
        $single = array();
        foreach ($row as $field => $value){
            if(!isset($value)){
                $single[] = '';
            }else{
                $single[] = addslashes($value);
            }
        }

        $values[] = "('" .  implode('\',\'', $single) . "')";
    }

    $scols = implode("`,`", $cols);
    $values = implode(",", $values);
    $sql = "INSERT INTO  `{$tablename}` (`{$scols}`) VALUES {$values}";
    if($need_update == true){
        $update_str = duplicateUpdate($cols);
        $sql .= $update_str;
    }
    $result = mysql_query($sql);

    if($result){
        return $result;
    }else{
        return false;
    }
}


function insert($array, $tablename, $need_update = false ) {
	connect_mysql();
    if (!is_array( $array))
    {
        $this->halt( "方法 insert() 第1个参数不是数组错误， 表名为 {$tablename} ");
        return false;
    }
    $cols = $values = '';
    foreach($array as $key=>$val)
    {
        $values .= "'" . addslashes($val) . "',";
        $cols .= "`" . trim($key) . "`,";
    }

    $cols   = rtrim( $cols, ',');
    $values = rtrim( $values, ',');
    $sql    = "INSERT INTO `{$tablename}` ({$cols}) VALUES ({$values})";
    if($need_update == true){
        $sql .= duplicateUpdate(array_keys($array));
    }
    if ( self::$debug)
    {
        echo "插入数组语句：".$sql."\n";
    }
    $result= mysql_query($sql);

    if($result){
        return true;
    }else{
        return false;
    }
}

function duplicateUpdate($fields){
	connect_mysql();
    //增加update
    $sql = " ON DUPLICATE KEY UPDATE ";
    $update_str = '';
    foreach($fields as $field)
    {
        $update_str .= "`" . $field . "` = VALUES(`" . $field . "`),";
    }
    $update_str = substr($update_str, 0 , -1);
    $sql .= $update_str;
    return $sql;
}


function replaceAll($url,$val) {
    foreach ($val as $i => $k) {
        $regex = '{#'.$i.'}';
        $url = str_replace($regex,$k,$url);
    }
    return $url;
}
function cache($url, $content='', $dir = 'E:\clone\baidu/robot/') {
    //&ak={#keyapi}&
    if (!is_dir($dir)) {
        mkdir($dir);
    }
    $file = md5($url);
    $path = '/' . substr($file, 0, 3) . '/' . substr($file, 3, 3) . '/';

    $new_file = md5(str_replace('&ak='.$_GET["key"], '', $url));
    $new_path = '/' . substr($new_file, 0, 3) . '/' . substr($new_file, 3, 3) . '/';
    if (!is_dir($dir . $new_path)) {
        mkdir($dir. $new_path, '0777',true);
    }
    if (is_file($dir . $path . $file)) {
        @copy($dir . $path . $file, $dir. $new_path . $new_file); //拷贝到新目录
        unlink($dir . $path . $file); //删除旧目录下的文件
    }
    if (is_file($dir . $file)) {
        @copy($dir . $file, $dir. $new_path . $new_file); //拷贝到新目录
        unlink($dir . $file); //删除旧目录下的文件
    }
    $file = $new_path . $new_file;
    if ($content == '' && is_file($dir . $file)) {
        return unserialize(file_get_contents($dir . $file));
    } else {
        file_put_contents($dir . $file, serialize ( $content ));
        return $content;
    }
}

function geoconv($coords, $from=6, $to=5, $ak='vqONULhld1YdvjPVELL610QY') {
    global $url_list;
    $api = 'http://api.map.baidu.com/geoconv/v1/?';
    $param = array(
        'coords' => '',
        'from' => $from,
        'to' => $to,
        'ak' => $ak,
    );
    if (!is_array($coords)) {
        $param['coords'] = $coords;
        $url = $api . http_build_query($param);
        $url_list[md5($url)] = array(
            'url' => $url,
            'coords' => $coords,
        );
    } else {
        while ($c = array_splice($coords, 0, 100)) {
            $param['coords'] = implode(";", $c);
            $url = $api . http_build_query($param);
            $url_list[md5($url)] = array(
                'url' => $url,
                'coords' => implode(";", $c),
            );
        }
    }
    $CurlMulti = new CurlMulti();
    $CurlMulti->cache = array (
        'dir' => 'E:\clone\baidu\geo',
        'on' => true,
        'expire' => 3600 * 2400,
        'dirLevel' => 2
    );
    $CurlMulti->maxThread = 50;
    // 对所有任务有效，可以被add()参数中的opt覆盖。
    $CurlMulti->opt[CURLOPT_CONNECTTIMEOUT] = 100;
    foreach ($url_list as $md5 => $item) {
        $CurlMulti->add(array(
            'url' => $item['url'],
            'args'=> array('key'=> $md5),
        ), function ($r, $args){
            global $url_list;
            if (strpos($r['content'], '{"status":0,') !== false) {
                $url_list[$args['key']]['res'] = $r['content'];
            }
        });
    }
    $CurlMulti->start();
    $result = array();
    foreach ($url_list as $md5 => $item) {
        $coords = explode(";", $item['coords']);
        if (isset($item['res'])) {
            $res = json_decode($item['res'], true);
            $result = array_merge($result, array_combine($coords, $res['result']));
        }
    }
    
    return $result;
}

function getGeo($client='116.455888,39.899355', $limit = 10000, $level=0, $u = array('x' => 0.015,'y' => 0.01)) {
    
    $clients[$client] = false;
    $list = array();
    while(true) {
        list($client, $val) = each($clients);
        list($x, $y) = explode(",",$client);

        $list[($x-$u['x']) . ',' . $y] = array(
            'left_down' => array(
                'x' => $x-$u['x'],
                'y' => $y
            ),
            'right_top' => array(
                'x' => $x,
                'y' => $y+$u['y']
            )
        );
        $list[($x-$u['x']) . ',' . ($y-$u['y'])] = array(
            'left_down' => array(
                'x' => $x-$u['x'],
                'y' => $y-$u['y'],
            ),
            'right_top' => array(
                'x' => $x,
                'y' => $y
            )
        );
        $list[$x . ',' . ($y-$u['y'])] = array(
            'left_down' => array(
                'x' => $x,
                'y' => $y-$u['y'],
            ),
            'right_top' => array(
                'x' => $x+$u['x'],
                'y' => $y
            )
        );
        $list[$x . ',' . $y] = array(
            'left_down' => array(
                'x' => $x,
                'y' => $y,
            ),
            'right_top' => array(
                'x' => $x+$u['x'],
                'y' => $y+$u['y']
            )
        );

        if ($limit >= count($list)) {
            $clients[($x+$u['x']) .','. ($y+$u['y'])] = false;
            $clients[($x+$u['x']) .','. ($y-$u['y'])] = false;
            $clients[($x-$u['x']) .','. ($y+$u['y'])] = false;
            $clients[($x-$u['x']) .','. ($y-$u['y'])] = false;
        } else {
            break;
        }

    }

    return $list;

}